package com.yztc.orangeentertainment.ui.login.phonelogin;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.media.Image;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.yztc.orangeentertainment.App;
import com.yztc.orangeentertainment.R;
import com.yztc.orangeentertainment.base.BaseActivity;
import com.yztc.orangeentertainment.bean.UserBean;
import com.yztc.orangeentertainment.ui.main.MainActivity;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.bmob.sms.BmobSMS;
import cn.bmob.sms.exception.BmobException;
import cn.bmob.sms.listener.RequestSMSCodeListener;
import cn.bmob.sms.listener.VerifySMSCodeListener;

/**
 * Created by My on 2016/10/21.
 */
public class PhoneRegisterActivity extends BaseActivity implements View.OnClickListener {
    @InjectView(R.id.et_reg_phone)
    EditText etRegPhone;
    @InjectView(R.id.et_reg_pwd)
    EditText etRegPwd;
    @InjectView(R.id.et_reg_mes)
    EditText etRegMes;
    @InjectView(R.id.Message_btn)
    Button Message_btn;
    @InjectView(R.id.reg_btn)
    Button regBtn;
    private ImageView iv;
    private AnimationDrawable drawable;
    @Override
    public int getLayoutId() {
        return R.layout.activity_register_phone;
    }

    @Override
    public void onClick(View v) {
        final String userName = etRegPhone.getText().toString();
        String yanzhengma = etRegMes.getText().toString();
        final String password = etRegPwd.getText().toString();

        switch (v.getId()) {
            case R.id.reg_btn:
                Log.e("MESSAGE:", "5");
                if (userName.length() == 0 || yanzhengma.length() == 0 || userName.length() != 11) {
                    Log.e("MESSAGE:", "6");
                    Toast.makeText(this, "手机号或验证码输入不合法", Toast.LENGTH_SHORT).show();
                } else {
                    App.killActivity(PhoneLoginActivity.class);
                    BmobSMS.verifySmsCode(this, userName, yanzhengma, new VerifySMSCodeListener() {
                        @Override
                        public void done(BmobException e) {
                            if (e == null) {
                                Log.e("MESSAGE:", "7");
                                Toast.makeText(PhoneRegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                                UserBean userBean = new UserBean();
                                userBean.setId(userName);
                                userBean.setUserName("手机用户" + userName.substring(userName.length() - 4, userName.length()));
                                userBean.setPsw(password);
                                App.getLiteOrm().insert(userBean);
                                Intent intent=new Intent(PhoneRegisterActivity.this, MainActivity.class);
                                intent.putExtra("id",userName);
                                intent.putExtra("tag",1);
                                startActivity(intent);
                                finish();
                            } else {
                                Log.e("MESSAGE:", "8");
                                Toast.makeText(PhoneRegisterActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }
                break;
            case R.id.Message_btn:
                if (userName.length() != 11) {
                    Toast.makeText(this, "请输入11位有效手机号码", Toast.LENGTH_SHORT).show();
                } else {
                    List<UserBean> list = App.getLiteOrm().query(UserBean.class);
                    for (int i = 0; i < list.size(); i++) {
                        if (userName.equals(list.get(i).getId())) {
                            Toast.makeText(PhoneRegisterActivity.this, "该手机号已经注册过了，可直接登录", Toast.LENGTH_SHORT).show();
                            break;
                        }
                    }
                    Log.e("MESSAGE:", "3");
                    //进行获取验证码操作和倒计时1分钟操作
                    BmobSMS.requestSMSCode(this, userName, "短信模板", new RequestSMSCodeListener() {
                        @Override
                        public void done(Integer integer, BmobException e) {
                            if (e == null) {
                                //发送成功时，让获取验证码按钮不可点击，且为灰色
                                Message_btn.setClickable(false);
                                Message_btn.setBackgroundColor(Color.GRAY);
                                Toast.makeText(PhoneRegisterActivity.this, "验证码发送成功，请尽快使用", Toast.LENGTH_SHORT).show();
                                /**
                                 * 倒计时1分钟操作
                                 * 说明：
                                 * new CountDownTimer(60000, 1000),第一个参数为倒计时总时间，第二个参数为倒计时的间隔时间
                                 * 单位都为ms，其中必须要实现onTick()和onFinish()两个方法，onTick()方法为当倒计时在进行中时，
                                 * 所做的操作，它的参数millisUntilFinished为距离倒计时结束时的时间，以此题为例，总倒计时长
                                 * 为60000ms,倒计时的间隔时间为1000ms，然后59000ms、58000ms、57000ms...该方法的参数
                                 * millisUntilFinished就等于这些每秒变化的数，然后除以1000，把单位变成秒，显示在textView
                                 * 或Button上，则实现倒计时的效果，onFinish()方法为倒计时结束时要做的操作，此题可以很好的
                                 * 说明该方法的用法，最后要注意的是当new CountDownTimer(60000, 1000)之后，一定要调用start()
                                 * 方法把该倒计时操作启动起来，不调用start()方法的话，是不会进行倒计时操作的
                                 */
                                new CountDownTimer(60000, 1000) {
                                    @Override
                                    public void onTick(long millisUntilFinished) {
                                        Message_btn.setBackgroundResource(R.drawable.button_shape02);
                                        Message_btn.setText(millisUntilFinished / 1000 + "秒");
                                    }

                                    @Override
                                    public void onFinish() {
                                        Message_btn.setClickable(true);
                                        Message_btn.setBackgroundResource(R.drawable.button_shape);
                                        Message_btn.setText("重新发送");
                                    }
                                }.start();
                                Log.e("MESSAGE:", "4");
                            } else {
                                Toast.makeText(PhoneRegisterActivity.this, "验证码发送失败，请检查网络连接", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });

                }
                break;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.inject(this);
        //初始化Bmob短信
        BmobSMS.initialize(PhoneRegisterActivity.this, "fa14c359e50d722e4b6397cefb92eae8");
        initView();
    }

    private void initView() {
        Message_btn.setOnClickListener(this);
        regBtn.setOnClickListener(this);
        iv= (ImageView) findViewById(R.id.iv__reg_anim);
        drawable= (AnimationDrawable) iv.getDrawable();

    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        drawable.start();
    }
}
